//
//  AppDelegate.m
//  Dear
//
//  Created by 陈俊俊 on 15/7/11.
//  Copyright (c) 2015年 陈俊俊. All rights reserved.
//

#import "AppDelegate.h"
#import "LoginViewController.h"
#import "InitViewController.h"
#import <BaiduMapAPI/BMapKit.h>
#import "TabBarController.h"
#import <AVFoundation/AVFoundation.h>
#import "UploadRequest.h"
@interface AppDelegate ()<BMKGeneralDelegate,UIAlertViewDelegate>
{
    BMKMapManager* _mapManager;
}
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
       
    // 要使用百度地图，请先启动BaiduMapManager
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"T5YIKYwEhdqEGSSXjfqTQL3a" generalDelegate:self];
    
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    //判断是否是第一次登陆
    NSUserDefaults *df = [NSUserDefaults standardUserDefaults];
    BOOL isFirst = [df boolForKey:@"first"];
    if (isFirst) {
        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[LoginViewController new]];
    }else{
        InitViewController *ivc = [InitViewController new];
        self.window.rootViewController = ivc;
    }
    [df setValue:@"YES" forKey:@"first"];
    [df synchronize];

    NSError *setCategoryErr = nil;
    NSError *activationErr  = nil;
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
    [[AVAudioSession sharedInstance] setActive: YES error: &activationErr];
    
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}





- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    [BMKMapView willBackGround];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
    if ([DearUser sharedInstance].userId != nil && ![[DearUser sharedInstance].userId isEqualToString:@""]) {
        [[UploadRequest sharedInstance].timer setFireDate:[NSDate distantPast]];
    }
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     [BMKMapView didForeGround];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

- (void)changeUUIDLogin:(NSString *)name
{
    if ([name isEqualToString:UUIDStr]) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"用户已经在其他设备上登录，你已被迫下线" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([self.window.rootViewController isKindOfClass:NSClassFromString(@
"TabBarController")]) {
        self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[LoginViewController new]];
    }
}

@end
